import React, { FC, useEffect, useRef, useState } from 'react';
import Engine, { EngineInterface } from '@aomao/engine';
import Bold from '@aomao/plugin-bold';
import CodeBlock, { CodeBlockComponent } from '@aomao/plugin-codeblock';
import Toolbar, { ToolbarPlugin, ToolbarComponent } from '@aomao/toolbar';
import MarkdownIt from 'markdown-it';

const AoMaoEditor: FC = () => {
  // 编辑器容器
  const ref = useRef<HTMLDivElement | null>(null);
  // 引擎实例
  const [engine, setEngine] = useState<EngineInterface | any>();
  // 编辑器内容
  const [content, setContent] = useState<string>('Hello word!');

  useEffect(() => {
    if (!ref.current) return;
    // 实例化引擎
    const engine = new Engine(ref.current, {
      plugins: [Bold, CodeBlock, ToolbarPlugin],
      cards: [CodeBlockComponent, ToolbarComponent],
    });
    // 设置编辑器值
    engine.setValue(content);
    // 监听编辑器值改变事件
    engine.on('change', () => {
      const value = engine.getValue();
      console.log(value);

      setContent(value);
    });

    engine.messageConfirm = async (msg: string) => {
      console.log(msg);

      return true;
    };

    // 设置引擎实例
    setEngine(engine);
    const md = new MarkdownIt();
    const result = md.render('# markdown-it rulezz!');
    console.log(result);
    engine.setMarkdown(result, (count) => {
      console.log(count);
    });
  }, []);

  return (
    <>
      {engine && <Toolbar engine={engine} items={[['bold']]} />}
      <div ref={ref}></div>
    </>
  );
};

export default AoMaoEditor;
